package cc.vv.lkrouter.router;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import java.util.concurrent.ConcurrentHashMap;

import cc.vv.lkrouter.inter.RouterInter;

/**
 * Activity路由
 *
 * @author: NPF
 * @date: 2018/3/12.
 */
public class RouterActivity implements RouterInter<Activity, Class<? extends Activity>> {
    /**
     * 路由缓存
     */
    private ConcurrentHashMap<String, Class<? extends Activity>> mClassZ = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, Activity> mClassA = new ConcurrentHashMap<>();

    private static RouterActivity mInstance;

    private RouterActivity() {
    }

    public static RouterActivity getinstance() {
        if (null == mInstance) {
            synchronized (RouterActivity.class) {
                if (null == mInstance) {
                    mInstance = new RouterActivity();
                }
            }
        }
        return mInstance;
    }

    /**
     * Activity实例配置
     *
     * @param key      唯一键
     * @param activity Activity实例
     */
    @Override
    public void routerT(String key, Activity activity) {
        Activity cacheActivity = mClassA.get(key);
        if (null == cacheActivity || activity != cacheActivity) {
            mClassA.put(key, activity);
        }
    }

    /**
     * Activity实例获取
     *
     * @param key 唯一键
     * @return Activity实例
     */
    @Override
    public Activity invokT(String key) {
        return mClassA.get(key);
    }

    /**
     * 保存路由数据
     *
     * @param key    唯一键
     * @param classz 对应字节码
     */
    @Override
    public void routerV(String key, Class<? extends Activity> classz) {
        Class cacheClass = mClassZ.get(key);
        if (null == cacheClass || classz != cacheClass) {
            mClassZ.put(key, classz);
        }
    }

    @Override
    public Class<? extends Activity> invokV(String key) {
        return mClassZ.get(key);
    }

    /**
     * 获取Activity的Intent
     *
     * @param context 上下文
     * @param key     唯一键
     * @return Intent
     */
    public Intent invok(Context context, String key) {
        Intent intent = null;
        Class<? extends Activity> classz = invokV(key);
        if (null != classz && null != context) {
            intent = new Intent(context, classz);
        }
        return intent;
    }
}
